package site.xuxingcan.contactchange;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private File mFile = new File(Environment.getExternalStorageDirectory(), "temp");
    private EditText count;
    private Button refresh;
    private TextView surplus;
    private TextView file_name;
    private Handler mHandler;
    private Button read;
    private Button clear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler(Looper.getMainLooper());
        count = (EditText) findViewById(R.id.count);
        refresh = (Button) findViewById(R.id.refresh);
        surplus = (TextView) findViewById(R.id.surplus);
        file_name = (TextView) findViewById(R.id.file_name);
        read = (Button) findViewById(R.id.read);
        clear = (Button) findViewById(R.id.clear);
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mFile == null || !mFile.exists() || mFile.isDirectory()) {
                    Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_LONG).show();
                } else {
                    try {
                        String s = readFileSdcardFile(mFile.getAbsolutePath());
                        String[] phones = s.split("\n");
                        surplus.setText("剩余未导入数量：" + phones.length);
                        Toast.makeText(MainActivity.this, "刷新成功", Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "刷新失败\n" + e, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mFile == null || !mFile.exists() || mFile.isDirectory()) {
                    Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_LONG).show();
                } else {
                    read.setEnabled(false);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                int cou = Integer.parseInt(count.getText().toString());
                                String s = readFileSdcardFile(mFile.getAbsolutePath());
                                String[] phones = s.split("\n");
                                ArrayList<String> phoneList = new ArrayList<String>();
                                for (String p : phones) {
                                    phoneList.add(p);
                                }
                                int size = phoneList.size();
                                for (int i = 0; i < size && i < cou; i++) {
                                    ContactUtil.AddContact(MainActivity.this, phoneList.remove(0));
                                }
                                String res = "";
                                for (String p : phoneList) {
                                    res += p + "\n";
                                }
                                writeFileSdcardFile(mFile.getAbsolutePath(), res);
                                final int p = phoneList.size();
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        read.setEnabled(true);
                                        surplus.setText("剩余未导入数量：" + p);
                                        Toast.makeText(MainActivity.this, "写入联系人成功", Toast.LENGTH_LONG).show();
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        read.setEnabled(true);
                                        Toast.makeText(MainActivity.this, "写入联系人失败", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }
                    }).start();
                }
            }
        });
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clear.setEnabled(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ContactUtil.DeleteAll(MainActivity.this);
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    clear.setEnabled(true);
                                    Toast.makeText(MainActivity.this, "清空联系人成功", Toast.LENGTH_LONG).show();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    clear.setEnabled(true);
                                    Toast.makeText(MainActivity.this, "清空联系人失败", Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
        findViewById(R.id.choose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showFileChooser();
            }
        });
        if (!SharedPreferenceUtil.getInstance(this).getIsOk()) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.dialog, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("请输入密码")
                    .setView(layout)
                    .setCancelable(false);
            final AlertDialog dialog = builder.show();
            final EditText key = (EditText) layout.findViewById(R.id.key);
            View confirm = layout.findViewById(R.id.confirm);
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (key.getText().toString().equals("zx12cv34")) {
                        dialog.dismiss();
                        SharedPreferenceUtil.getInstance(MainActivity.this).setIsOk(true);
                    } else {
                        Toast.makeText(MainActivity.this, "密码错误，请重新输入！", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
        if (SharedPreferenceUtil.getInstance(this).getPath() != null) {
            File f = new File(SharedPreferenceUtil.getInstance(this).getPath());
            file_name.setText("当前文件名：" + f.getName());
        }
    }

    private static final int FILE_SELECT_CODE = 111;

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    String path = getPath(this, uri);
                    if (path == null) {
                        Toast.makeText(this, "文件选择出错", Toast.LENGTH_LONG).show();
                    } else {
                        File f = new File(path);
                        if (f != null && f.exists() && f.isFile()) {
                            file_name.setText("当前文件名：" + f.getName());
                            SharedPreferenceUtil.getInstance(MainActivity.this).setPath(path);
                            copyFile(f.getAbsolutePath(), mFile.getAbsolutePath());
//                            mFile = f;
                            refresh.performClick();
                        } else {
                            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
                        }
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void copyFile(String oldPath, String newPath) {
        try {
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, length);
                }
                inStream.close();
                fs.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }

    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    //写数据到SD中的文件
    public void writeFileSdcardFile(String fileName, String write_str) throws Exception {
        FileOutputStream fout = new FileOutputStream(fileName);
        byte[] bytes = write_str.getBytes();
        fout.write(bytes);
        fout.close();
    }


    //读SD中的文件
    public String readFileSdcardFile(String fileName) throws Exception {
        String res = "";
        FileInputStream fin = new FileInputStream(fileName);
        int length = fin.available();
        byte[] buffer = new byte[length];
        fin.read(buffer);
        res = new String(buffer, "UTF-8");
        fin.close();
        return res;
    }
}